package com.term.util.locator;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.ListableBeanFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chenGang on 2017/1/11.
 */
public class BeanLocator implements BeanFactoryAware {
    private static BeanFactory beanFactory;
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        beanFactory = beanFactory;
    }

    public static BeanFactory getBeanFactory() {
        return beanFactory;
    }

    public static Object findBeanByName(String name) {
        Object obj = null;

        try {
            obj = beanFactory.getBean(name);
        } catch (Exception var3) {
            ;
        }

        return obj;
    }

    private static <T> Map<String, T> beanOfTypeIncludingAncestors(Class<T> type) {
        return (Map)(beanFactory instanceof ListableBeanFactory ? BeanFactoryUtils.beansOfTypeIncludingAncestors((ListableBeanFactory)beanFactory, type):new HashMap());
    }

    public static <T> List<T> getAllBeans(Class<T> type) {
        Map map = beanOfTypeIncludingAncestors(type);
        return new ArrayList(map.values());
    }
}
